<template>
  <div class="searchContainer" v-if="!isDetail">
    <div class="header">
      <form action="/">
        <van-search
          class="search"
          v-model="value"
          show-action
          :placeholder="defaultKeyword.keyword"
          @update:model-value="onSearch"
          @clear="onCancel"
          @cancel="onCancel"
          @search="toSearch"
        />
      </form>
    </div>
    <div class="takeNotes" v-if="isSearch">
      <div class="historyTake" v-if="searchList">
        <div class="takeHeader">
          <div class="text">历史记录</div>
          <van-icon class="icon" name="delete-o" @click="clearHistory" />
        </div>
        <div class="takeBody">
          <van-tag
            class="takeItem"
            plain
            size="medium"
            color="#999"
            text-color="#333"
            type="primary"
            v-for="history in searchList"
            @click="toDeatil(history)"
            >{{ history }}</van-tag
          >
        </div>
      </div>
      <div class="historyTake">
        <div class="takeHeader">
          <div class="text">热门搜索</div>
        </div>
        <div class="takeBody">
          <van-tag
            class="takeItem"
            v-for="item in hotKeywordVOList"
            plain
            :class="{ active: item.highlight }"
            size="medium"
            type="primary"
            @click="toDeatil(item.keyword)"
            >{{ item.keyword }}</van-tag
          >
        </div>
      </div>
    </div>

    <!-- 搜索弹出框 -->
    <div class="searchList" v-if="value !== ''">
      <div class="searchItem" v-for="(item, index) in searchAutoData" :key="index" @click="toDeatil(item)">
        <div class="text">{{ item }}</div>
        <div class="iconBox">
          <van-icon name="arrow" class="icon" />
        </div>
      </div>
    </div>
  </div>
  <detail v-else :value="value" @isDetailFun="isDetailFun"></detail>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'Search'
})
</script>
<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { showToast } from 'vant'
import { storeToRefs } from 'pinia'
import { userSearchStore } from '@/stores/modules/search'
import detail from './componts/searchDetail.vue'
import { useRouter, useRoute } from 'vue-router'
import _ from 'lodash'
// 路由实例
const router = useRouter()
const route = useRoute()
// store仓库
const searchStore = userSearchStore()
const { defaultKeyword, searchAutoData, hotKeywordVOList } = storeToRefs(searchStore)
// 用户输入的值
const value = ref<string>('')
// 控制是否搜索属性
const isSearch = ref<boolean>(true)

// 用户输入时实时搜索 防抖处理
const onSearch = _.debounce((val: string) => {
  if (value.value.trim() !== '') {
    searchStore.getSearchAutoData(val)
    isSearch.value = false
  } else {
    isSearch.value = true
  }
}, 1000)

// 点击取消返回上一页面
const onCancel = () => {
  showToast('')
  router.go(-1)
}
// 调用首页热搜
const getSearchKeywords = async () => {
  searchStore.getSearchData()
}

// 搜索历史记录
const searchList = ref<string[]>([])
// 搜索
const toSearch = (val: string) => {
  if (val.trim() !== '') {
    isSearch.value = true
    isDetail.value = true

    router.push(`/search?keyword=${value.value}`)
    addHistory(val)
  }
}

// 添加历史记录
const addHistory = (val: string) => {
  if (searchList.value.some((item) => item === val)) return
  searchList.value.unshift(val)
  localStorage.setItem('user_searchList', JSON.stringify(searchList.value))
}
// 获取历史记录
const getHistory = () => {
  const newHistory = localStorage.getItem('user_searchList')

  if (newHistory !== 'null') {
    searchList.value = JSON.parse(newHistory as string)
  }
}

// 点击跳转detail页面
const toDeatil = (keyWord: string) => {
  value.value = keyWord
  isSearch.value = true
  isDetail.value = true
  router.push(`/search?keyword=${keyWord}`)
}

// 清除历史记录
const clearHistory = () => {
  searchList.value = []

  localStorage.setItem('user_searchList', JSON.stringify(searchList.value))
}

// 自定义事件收集子传来的数据
const isDetailFun = (emitIsDetail: boolean) => {
  isDetail.value = false
  isSearch.value = false
}

// 商品详情逻辑
const isDetail = ref<boolean>(false)
onMounted(() => {
  getSearchKeywords()
  getHistory()
  value.value = ''
})
</script>

<style lang="less" scoped>
.searchContainer {
  width: 100%;
  height: 100vh;
  background-color: #eeeeee;
  .header {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
    .search {
      width: 360px;
      height: 28px;
      padding: 0 10px;
      border-radius: 8px;
    }
  }
  .historyTake {
    width: 345px;
    padding: 0 15px 15px 15px;
    margin-bottom: 10px;
    display: flex;
    overflow: hidden;
    flex-direction: column;
    background-color: #ffffff;
    .takeHeader {
      height: 45px;
      font-size: 14px;
      color: #999;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .text {
        width: 56px;
        height: 21px;
      }
      .icon {
        font-size: 18px;
        color: #333;
      }
    }
    .takeBody {
      width: 375px;
      background-color: #ffffff;
      .takeItem {
        height: 23px;
        border-radius: 15%;
        margin: 0 16px 16px 0;
        padding: 0 7.5px;
        color: #333;
        border-color: #999;
        // max-width: 90px;
        // overflow: hidden;
        // text-overflow: ellipsis;
        // white-space: nowrap;
        &.active {
          border-color: #dd1a21;
          color: #dd1a21;
        }
      }
    }
  }

  .searchList {
    width: 375px;
    padding-left: 15px;
    background-color: white;
    .searchItem {
      width: 360px;
      height: 45px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #999;
      box-sizing: content-box;

      .text {
        font-size: 14px;
        color: #333;
      }
      .iconBox {
        margin-right: 10px;
        .icon {
          color: #333;
          font-size: 16px;
        }
      }
    }
    .searchItem:last-child {
      border: 0px;
    }
  }
}
</style>
